<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<link rel="stylesheet" type="text/css" media="screen" href="css/redmond/jquery-ui-1.10.3.custom.min.css" />	<!-- jqueryUI CSS -->
<link rel="stylesheet" type="text/css" media="screen" href="css/selfTemplate.css" />	<!-- 本專案自行定義 CSS -->

<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>			<!-- jquery 函式庫 -->
<script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>	<!-- jqueryUI 核心 -->
<script src="js/jquery.cookie.js" type="text/javascript"></script>				<!-- 操作cookie用 -->
<script src="js/widgets.js" type="text/javascript"></script> 					<!-- 本專案自行定義 JS -->


<script type="text/javascript">

var isCrashed = false;

function validate(obj) {
	isCrashed = false
	
	clearErrorMsg();
	$("#dd").html("");
	if ( $("input[name='emer']:checked").val() == undefined ) {
		$("#errShortMsg").html("請選擇是否為緊急上線");
	} else if ( $("input[name='env']:checked").val() == undefined ) {
		$("#errShortMsg").html("請選擇欲部署的環境");
	} else {
		windowFreeze("先檢查環境"+$("input[name='env']:checked").val()+"，相關資訊是否設定完整...");
		$.ajax({type:"post",url:"ValidateEnv4Dep",dataType:"json",async:false,
			data:{ subsysId:"fOrder",envId:$("input[name='env']:checked").val() },
			success : function(res) {
				if( res.i1 != 99 ) {
					$("#errShortMsg").html(res.s1);
				} else {
					windowUnfreeze();
					
					var constraint = "subsysId"+splitTokenONE+"fOrder"+splitTokenFOUR+"envId"+splitTokenONE+$("input[name='env']:checked").val();
					var isArtificialCheckNeed = getTableColumnValue("env","isArtificialCheckNeed",constraint);
					
					if( isArtificialCheckNeed=='f' ) {
						windowFreeze("檢查完成，進行部署...");
					}
					
					
					dep(obj);
				}
			},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
		});
		windowUnfreeze();
	}
}

//申請部署許可
function apply4Deploy(obj) {
	clearErrorMsg();
	
	//是否部署需要經過申請
	var isDepApplyNeed = getSysParameter("isDepApplyNeed");
	var tarDeliverySN = $(obj).attr("tarDeliverySN");
	var targetSystemId = $(obj).attr("targetSystemId");
	var deliverySN = $(obj).attr("deliverySN");
	
	var statusSN = 6;
	$("button[tarDeliverySN='"+tarDeliverySN+"']").attr("statusSN", statusSN );	//6 已部署待確認
	$("button[tarDeliverySN='"+tarDeliverySN+"']").parent("td").next().next().next().html("已提領待送審");
	$.ajax({type:"post",url:"UpdateDeltaskStatus",dataType:"text",async:false,
		data:{ empId:$.cookie("empId"),statusSN:statusSN,tarDeliverySN:tarDeliverySN,targetSystemId:targetSystemId,deliverySN:deliverySN},
		success : function(res) {
			if( isDepApplyNeed === "true" ) {
				$("button[tarDeliverySN='"+tarDeliverySN+"']").attr("statusSN", 7 );	//7 已送審
				$("button[tarDeliverySN='"+tarDeliverySN+"']").attr("disabled", true );
				$("button[tarDeliverySN='"+tarDeliverySN+"']").parent("td").next().next().next().html("已送審");
			} else {
				validate(obj);
			}
		},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
	});
}

function deploy2ServerGroup(sq2,tarDeliverySN) {
	var sq = sq2.s1;
	var sqIP = sq2.s2;
	/*
		0	初始化，尚未動作
		1	必須執行啟閉HTTPD，但尚未執行關閉
		2	關閉HTTPD成功，準備開始部署
		3	不須執行關閉HTTPD，準備開始部署
	   	4	必須執行啟閉HTTPD，執行關閉失敗
		5	不須執行關閉HTTPD，部署失敗
		6	關閉HTTPD成功，部署失敗
		7	不須執行關閉HTTPD，部署成功
		8	關閉HTTPD成功，部署成功
	   10	關閉HTTPD成功，執行開啟成功
	   12	關閉HTTPD成功，執行開啟失敗
	*/
	
	
	//0	初始化，尚未動作
	var depStatus = 0;	//部署特定 server group的執行狀態

		/*
			1. 關閉每台機器的 http 服務	<主機為層級>
			2. 將檔案部署至 Server Group的 Management Console <Server Group為層級>
			3. 開啟每台機器的 http 服務	<主機為層級>
		*/
	windowFreeze("部署至"+sq+"\t("+sqIP+")");
		
	$("#dd").append("\n\n開始處理 "+sq+"\t("+sqIP+")");
	$("#dd").append("\n\ta. 關閉下轄主機Httpd Service...");
	var apURL ="";
	var apPort ="";
	var squadId = sq;
	
	if( isPerformHTTPD === 'true') {
		depStatus=1;
	
		//取得 SQUAD下的主機，以關閉每台機器的 http 服務
		$.ajax({type:"post",url:"HostInSquad",dataType: "json",async:false,
			data:{subsysId:"fOrder",envId:$("input[name='env']:checked").val(),squadId:squadId,depmainSN:depmainSN},
			success : function(reses) {
				if( reses.length > 0 ) {
					$.each(reses, function(i, res){
						apURL = res.s1;
						apPort = res.i1;
						$("#dd").append("\n\t\t"+(i+1)+".\t"+apURL+".....");
						
						//開始關閉HTTP SERVICE
						if ( apURL != "10.144.97.99" ) {
							$.ajax({type:"post",url:"SwitchHTTPservice",dataType:"text",async:false,
								data:{subsysId:"fOrder",envId:$("input[name='env']:checked").val(),actType:"stop",hostIP:apURL,port:apPort,depmainSN:depmainSN,squadId:squadId},
								success : function(res) {
									var tmp  = res;
									if(  tmp == "原本就未啟動" || tmp == "OK" ) {
										depStatus=2;	//2 關閉HTTPD成功，準備開始部署
									} else {
										depStatus=4;	//4 必須執行啟閉HTTPD，執行關閉失敗
										depFail(tarDeliverySN);
									}
								
									$("#dd").append(res);
								},error : function(xhr, ajaxOptions, thrownError) {
									depStatus=4;	//4 必須執行啟閉HTTPD，執行關閉失敗
									depFail(tarDeliverySN);
									errorAjx(xhr);
								}
							});
						} else {
							depStatus=3;	//3	不須執行關閉HTTPD，準備開始部署
							$("#dd").append("不動作");
						}
					});
				} else {
					depStatus=4;	//4 必須執行啟閉HTTPD，執行關閉失敗
					$("#dd").append("\n\n查無ServerGroup下轄主機記錄，動作暫停!");
					depFail(tarDeliverySN);
				}
			},error : function(xhr, ajaxOptions, thrownError) {
				depStatus=4;	//4 必須執行啟閉HTTPD，執行關閉失敗
				depFail(tarDeliverySN);
				errorAjx(xhr);
			}
		});
	} else {
		console.log("目前的狀態碼："+depStatus);
		depStatus=3;	//3	不須執行關閉HTTPD，準備開始部署
		$("#dd").append("略過");
	}
	
	//2  關閉HTTPD成功，準備開始部署
	//3  不須執行關閉HTTPD，準備開始部署
	if ( !isCrashed && (depStatus==2 || depStatus==3) ) {	
	
		//2. 將檔案部署至 Server Group的 Management Console <Server Group為層級>
		//開始部署檔案
		$("#dd").append("\n\tb. 開始部署檔案");
		$(files).each(function(a){
			//先假設部署失敗	
			//2 代表是執行第一個檔案，8代表第二個以上的檔案
			if( depStatus==2 || depStatus==8 ) {
				depStatus=6;	//6	關閉HTTPD成功，部署失敗
			} else {
				depStatus=5;	//5	不須執行關閉HTTPD，部署失敗
			}
		
			var fn = $(this).attr("fn");
			var ver = $(this).attr("ver");
			$("#dd").append("\n\t\t"+(a+1)+".\t"+fn);
			
			$("#dd").append("\n\t\t\t- 是否已存在......");
		
			$.ajax({type:"post",url:"IsFileExistInAP",dataType:"text",async:false,
				data:{subsysId:"fOrder",envId:$("input[name='env']:checked").val(),squadId:squadId,fn:fn,depmainSN:depmainSN},
				success : function(res) {
					var tmp = res;
					$("#dd").append(tmp);
					if (tmp === "存在")  {
						$("#dd").append("\n\t\t\t- 進行下線......");			
						$.ajax({type:"post",url:"UnDepAWE",dataType:"text",async:false,
							data:{subsysId:"fOrder",envId:$("input[name='env']:checked").val(),squadId:squadId,fn:fn,depmainSN:depmainSN},
							success : function(res) {
								if (res === 'true')  {
									$("#dd").append("成功");
								} else {
									$("#dd").append("失敗");
								}
							},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
						});
					}
				},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
			});
			
			$("#dd").append("\n\t\t\t- 進行部署......");
			
			$.ajax({type:"post",url:"DepAWE",dataType:"text",async:false,
				data:{subsysId:"fOrder",envId:$("input[name='env']:checked").val(),squadId:squadId,fn:fn,ver:ver,apIP:apURL,apPort:apPort,depmainSN:depmainSN},
				success : function(res) {
					var tmp = res;	//要換一個變數裝，才能使用....我也不知道為什麼
					if (tmp === "成功")  {
						console.log("部署"+fn+"成功，目前的狀態碼："+depStatus);
						if( depStatus==6 ) {
							depStatus=8;	//8	關閉HTTPD成功，部署成功
						} else {
							depStatus=7;	//7	不須執行關閉HTTPD，部署成功
						}
						$("#dd").append( tmp );
					} else {
						$("#dd").append("\n\n 發生錯誤，動作暫停 ");
						depFail(tarDeliverySN);
					}					
					
				},error : function(xhr, ajaxOptions, thrownError) { 
					$("#dd").append("\n\n 發生錯誤，動作暫停 ");
					depFail(tarDeliverySN);
					errorAjx(xhr); 
				}
			});
		});
		
		//7	不須執行關閉HTTPD，部署成功
		//8	關閉HTTPD成功，部署成功
		if ( depStatus==7 || depStatus==8 ) {
			
			//3. 開啟每台機器的 http 服務	<主機為層級>
			//取得 SQUAD下的主機，以關閉每台機器的 http 服務
			$("#dd").append("\n\tc. 開啟下轄主機Httpd Service...");
		
			if( depStatus==8 ) {
				$.ajax({type:"post",url:"HostInSquad",dataType: "json",async:false,
					data:{subsysId:"fOrder",envId:$("input[name='env']:checked").val(),squadId:squadId,depmainSN:depmainSN},
					success : function(reses) {
						if( reses.length > 0 ) {
							$.each(reses, function(i, res){
								apURL = res.s1;
								apPort = res.i1;
								$("#dd").append("\n\t\t"+(i+1)+".\t"+apURL+".....");
								
								if ( apURL != "10.144.97.99" ) {
									//開啟HTTP SERVICE
									$.ajax({type:"post",url:"SwitchHTTPservice",dataType:"text",async:false,
										data:{subsysId:"fOrder",envId:$("input[name='env']:checked").val(),actType:"start",hostIP:res.s1,port:res.i1,depmainSN:depmainSN,squadId:squadId},
										success : function(res) {
											var tmp  = res;
											if( tmp == "OK" ) {
												depStatus=10;	//10 關閉HTTPD成功，執行開啟成功
											} else {
												depStatus=12;	//12 關閉HTTPD成功，執行開啟失敗
											}
											$("#dd").append(res);
										},error : function(xhr, ajaxOptions, thrownError) {
											depStatus=12;	//12 關閉HTTPD成功，執行開啟失敗
											depFail(tarDeliverySN);
											errorAjx(xhr); }
									});
								} else {
									depStatus=10;	//10 關閉HTTPD成功，執行開啟成功
									$("#dd").append("不動作");
								}
							});
						} else {
							depStatus=12;	//12 關閉HTTPD成功，執行開啟失敗
							$("#dd").append("\n\n查無ServerGroup下轄主機記錄，動作暫停!");
							depFail(tarDeliverySN);
						}
					},error : function(xhr, ajaxOptions, thrownError) {
						depStatus=12;	//12 關閉HTTPD成功，執行開啟失敗
						$("#dd").append("\n\n查詢ServerGroup下轄主機發生錯誤，動作暫停!");
						depFail(tarDeliverySN);
						errorAjx(xhr);
					}
				});
			} else {
				console.log("目前的狀態碼："+depStatus);
				$("#dd").append("略過");
			}
			
			
			//7		不須執行關閉HTTPD，部署成功
	   		//10	關閉HTTPD成功，執行開啟成功
			if( depStatus==10 || depStatus==7 ) {
				var notPerformSize = $("select#selectNotPerformed option").size();	
				if ( notPerformSize == 0) {
					$("#dd").append("\n\n"+cdt()+"\n結束!");
			
					var ta = $("textarea#dd").val();	//textarea所輸出的值，代表執行的動
			
					var statusSN=11;	//預設需進行確認
					var isTestNeedConfirm = getSysParameter("isTestNeedConfirm");	
					/*	
						沒找到失敗這個詞，即代表成功，即有的記錄是預設失敗的
						若部署成功，才有必要去判斷是否要確認結果
					*/
					if ( ta.indexOf("失敗") == -1 && !isCrashed) {	
						$("button[tarDeliverySN='"+tarDeliverySN+"']").attr("statusSN", statusSN );	//11 已部署待確認
						$("button[tarDeliverySN='"+tarDeliverySN+"']").parent("td").next().next().next().html("已部署待確認");
						//為了可以重覆部署，故註解掉
						//$("button[tarDeliverySN='"+tarDeliverySN+"']").unbind("click").bind("click",function(){ apply4Deploy(obj); });
						$.ajax({type:"post",url:"UpdateDeltaskStatus",dataType:"text",async:false,
							data:{ empId:$.cookie("empId"),statusSN:statusSN,tarDeliverySN:tarDeliverySN,targetSystemId:targetSystemId,deliverySN:deliverySN},
							success : function(res) {
								if( isTestNeedConfirm !== "true" ) {
									$("button[tarDeliverySN='"+tarDeliverySN+"']").attr("statusSN", 12 );	//12 已確認成功
									$("button[tarDeliverySN='"+tarDeliverySN+"']").parent("td").next().next().next().html("已確認成功");
								}
							},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
						});
					
						//為了可以重覆部署，故註解掉
						//$("button[tarDeliverySN='"+tarDeliverySN+"']").attr("disabled", true );
					} else {
						depFail(tarDeliverySN);
					}
				}
			}
		}
		
		windowUnfreeze();
	} else {	//先前動作有問題，暫停執行
		$("#dd").append("\n\n 發生錯誤動作暫停!");
		depFail(tarDeliverySN);
	}
	if ( !(depStatus==7 || depStatus==10) ) {
		depFail(tarDeliverySN);
	}
}


//部署失敗時，修改畫面文字
function depFail(sn) {
	isCrashed=true;
	$("button[tarDeliverySN='"+sn+"']").attr("statusSN", 10 );	//10 部署失敗
	$("button[tarDeliverySN='"+sn+"']").parent("td").next().next().next().html("部署失敗");
	closeDialog("loading");
	closeDialog("dialogPerformDeployment");
}


//提領程式
function withdraw(obj) {
	clearErrorMsg();
	
	var tarDeplMainSN = $(obj).attr("tarDeplMainSN");
	var tarDeliverySN = $(obj).attr("tarDeliverySN");

	windowFreeze("提領程式中...");
	
	$.ajax({type:"post",url:"Withdraw4SDEL",dataType:"json",async:false,
		data:{ subsysId:"fOrder",empId:$.cookie("empId"),tarDeplMainSN:tarDeplMainSN,tarDeliverySN:tarDeliverySN },
		success : function(res) {
			if ( res['res'] == "OK" ) {
				$("button[tarDeliverySN='"+tarDeliverySN+"']").attr("statusSN", 6 );	//6 已提領待送審
				$("button[tarDeliverySN='"+tarDeliverySN+"']").parent("td").next().next().next().html("已提領待送審");
				
				$("button[tarDeliverySN='"+tarDeliverySN+"']").attr("deliverysn", res.deliverySN );
				$("button[tarDeliverySN='"+tarDeliverySN+"']").attr("deplmainsn", res.deplMainSN );
				$("button[tarDeliverySN='"+tarDeliverySN+"']").unbind("click");
				$("button[tarDeliverySN='"+tarDeliverySN+"']").bind("click",function(){ apply4Deploy(obj); });
				//$("button[tarDeliverySN='"+tarDeliverySN+"']").bind("click",function(){ validate(obj); });
				$("button[tarDeliverySN='"+tarDeliverySN+"']").parent("td").next().next().html(res.deliverySN+"("+tarDeliverySN+")");
				
				
				$("button[tarDeliverySN='"+tarDeliverySN+"']").parent("td").next().next().next().next().next().attr("deliverysn", res.deliverySN );
				$("button[tarDeliverySN='"+tarDeliverySN+"']").parent("td").next().next().next().next().next().next().attr("deliverysn", res.deliverySN );
				$("button[tarDeliverySN='"+tarDeliverySN+"']").parent("td").next().next().next().next().next().next().next().attr("deliverysn", res.deliverySN );
				
				var tmp=""
				$.each(res.fses, function(i,fs){
					tmp += "<li ver='"+fs.localVer+"' fn='"+fs.fileName+"'>"+fs.fileName+"&nbsp;"+fs.localVer+"("+fs.targetVer+")</li>";
				});
				$("button[tarDeliverySN='"+tarDeliverySN+"']").parent("td").next().next().next().next().next().next().next().next().children("ul").html(tmp);
			} else {
				$("#errShortMsg").html( res['res'] );
			}
		},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
	});
	
	windowUnfreeze();
}

function gg(tarDeliverySN) {
	var notPerformSize = $("select#selectNotPerformed option").size();
	var performedSize = $("select#selectPerformed option").size();
	
	var width=375;
	
	if( performedSize >0 && notPerformSize>0 ) {
		width=520;
	} else if( performedSize >0 && notPerformSize>0 ) {
		width=350;
	}
	
	if (　notPerformSize > 0　) {
		$("#dialogPerformDeployment").prop("title","選擇執行的Server Group").css("visibility", "visible").dialog({
			resizable:true,show:"fold",hide:"fold",width:width, async:false,
			buttons : {
				"執行部署" : function() {
					var serverGroupName = $("select#selectNotPerformed option:selected").attr("value");
					var serverGroup = $("select#selectNotPerformed option:selected").html();
					var sq2 = {s1:serverGroupName,s2: getInPar( serverGroup ) }
					
					if ( serverGroupName != undefined ) {
						$("select#selectNotPerformed option:selected").remove();
						var tmp = "<option value='"+ serverGroupName +"'>"+serverGroup+"</option>";
						$("select#selectPerformed").append(tmp);
						
						if (　notPerformSize == 1　) {
							$(this).dialog("close");
						} else {
							gg(tarDeliverySN);
						}
						
						if (!isCrashed) {
							deploy2ServerGroup(sq2,tarDeliverySN);
						}
					} else {
						alert("請選擇欲執行的群組");
					}
				}
			}
		});
	}
}


function dep(obj) {

	clearErrorMsg();
	
	//以下這幾個變數都是全域的
	depmainSN = 0;			 	//部署執行的ID
	deliverySN = $(obj).attr("deliverySN");
	tarDeliverySN = $(obj).attr("tarDeliverySN");
	deplmainSN = $(obj).attr("deplmainSN");		//部署計劃流水號
	targetSystemId =  $(obj).attr("targetSystemId");
	sqs = [];	//Squad列表
	hts = [];	//主機列表
	files = $(obj).parent().parent().children("td").children("ul.file").children("li");
	isPerformHTTPD = getSysParameter("isPerformHTTPD");	//部署時是否關閉httpd
	
	
	var constraint = "subsysId"+splitTokenONE+"fOrder"+splitTokenFOUR+"envId"+splitTokenONE+$("input[name='env']:checked").val();
	isArtificialCheckNeed = getTableColumnValue("env","isArtificialCheckNeed",constraint);	//這個環境的部署是否需要一個一個Server Group的確認
	
	//產生部署執行記錄
	$.ajax({type:"post",url:"CreateDepMain",dataType:"json",async:false,
		data:{ tarDeliverySN:tarDeliverySN,targetSystemId:targetSystemId,subsysId:"fOrder",envId:$("input[name='env']:checked").val(),empId:$.cookie("empId"),deliverySN:deliverySN,deplmainSN:deplmainSN,isUrgent:$("input[name='emer']:checked").val() },
		success : function(res) {
			depmainSN = res["s1"];
			$("td.lastDeployId[deliverySN='"+deliverySN+"']").html( depmainSN );
			$("td.lastDeployerName[deliverySN='"+deliverySN+"']").html( $.cookie("empName") );
			$("td.lastDeployDT[deliverySN='"+deliverySN+"']").html(res["s2"]);
		},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
	});
	
	
	$("#dd").html("開始!\n"+cdt()+"\n\n");
	$("#dd").append("本次上線序號："+ depmainSN );
	$("#dd").append("\n正在處理交付代號："+ deliverySN );
	$("#dd").append("\n取得【"+$("input[name='env']:checked").attr("envName")+"】環境下的 ServerGroup清單...");
	
	//取得 環境下的SQUAD
	$.ajax({type:"post",url:"SquadInEnv",dataType: "json",async:false,
		data:{subsysId:"fOrder",envId:$("input[name='env']:checked").val(),depmainSN:depmainSN},
		success : function(reses) {
			if( reses.length > 0 ) {
				$("select#selectNotPerformed option").remove();
				
				$.each(reses, function(i, res){
					//將 Server Group，加入顯示的 textarea
					$("#dd").append("\n"+(i+1)+".\t"+res.s1+"\t("+res.s2+")");
					
					//將 Server Group，加入未執行的SELECT中
					var tmp = "<option value='"+ res.s1 +"'>"+res.s1+" ("+res.s2+")</option>";
					$("select#selectNotPerformed").append(tmp);
					
					sqs.push(res);
				});
			} else {
				$("#dd").append("無記錄，動作暫停!");
				closeDialog("loading");
				closeDialog("dialogPerformDeployment");
			}
		},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
	});
	
	if ( isArtificialCheckNeed == 't' ){
		gg(tarDeliverySN);
	} else {
		$.each(sqs,function(i,sq){
			$("select#selectNotPerformed option[value='"+sq.s1+"']").remove();
			if (!isCrashed) {
				deploy2ServerGroup(sq,tarDeliverySN);
			}
		});
	}
}

$(document).ready(function() {
	init("sdep.html");
	$("#errShortMsg").html("");
	windowFreeze("畫面初始中");
	$("input[type='radio']").removeAttr('checked');
	
	
	$("select#selectPerformed").attr("readonly",true);
	
	$.ajax({type:"post",url:"QueryEnv",dataType: "json",async:false,
		data:{subsysId:'fOrder',fc:'selEnvBySubSys'},//fc的內容沒有意義，只是為了驅動後端讓它不要回傳grid用的格式
		success : function(reses) {
			if( reses.length > 0 ) {
				$.each(reses, function(i,res) {
					var tmp = "<input type='radio' name='env' id='env"+res.id+"' envName='"+res.name+"' value='"+res.id+"'><label for='env"+res.id+"'>"+res.name+"("+res.id+")</label>";
					$("#radioEnvSet").append(tmp);
				});
			}
		},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
	});
	
	
	$.ajax({type:"post",url:"Query4SDEP_2",dataType: "json",async:false,
		success : function(reses) {
			if( reses.isErrorHappened ) {
				$("#errShortMsg").html( reses.errorMesage );
			} else {
				
				var targetSystemId = reses.targetSystemId;			//從何而來
					
				var isDepApplyNeed = getSysParameter("isDepApplyNeed");		//是否部署需要經過申請
			
				$.each(reses.qdeps, function(i,res) {
					var idx = $("#tbodyFile tr").size()+1;
				
					var deliverySN = res.deliverySN;
					var statusSN = res.statusSN;
					
					if ( deliverySN == "0" ) {
						deliverySN = "";
					}
					
					if( idx  == 1 ) {
						tmp = "<tr><td rowspan=1 class='verTop left'><textarea cols=40 rows=60 id='dd' readonly></textarea></td><td class='center'><button type='button' class='engN' targetSystemId='"+targetSystemId+"' statusSN='"+statusSN+"' tarDeplMainSN='"+res.tarDeplmainSN+"' tarDeliverySN='"+res.deliveryTarSN+"' deplmainSN='"+res.deplmainSN+"' deliverySN='"+deliverySN+"'>GO</button</td><td class='int'>"+idx+"</td><td class='int'>"+deliverySN+"("+res.deliveryTarSN+")</td><td>"+res.statusDesc+"</td><td class='engN'>"+res.cdt+"</td><td deliverySN='"+deliverySN+"' class='int lastDeployId'>"+res.lastDeployId+"</td><td deliverySN='"+deliverySN+"' class='left zhTwN lastDeployerName'>"+res.lastDeployerName+"</td><td deliverySN='"+deliverySN+"' class='left engN lastDeployDT'>"+res.lastDeployDT+"</td><td><ul class='file engN'></ul></td><td><ul class='zhTwN req'></ul></td><td><textarea class='zhTwN' readonly>"+res.deliveryComment+"</textarea></td></tr>";
					} else {
						tmp = "<tr><td class='center'><button type='button' class='engN' targetSystemId='"+targetSystemId+"' statusSN='"+statusSN+"' tarDeplMainSN='"+res.tarDeplmainSN+"' tarDeliverySN='"+res.deliveryTarSN+"' deplmainSN='"+res.deplmainSN+"' deliverySN='"+deliverySN+"'>GO</button</td><td class='int'>"+idx+"</td><td class='int'>"+deliverySN+"("+res.deliveryTarSN+")</td><td>"+res.statusDesc+"</td><td class='engN'>"+res.cdt+"</td><td deliverySN='"+deliverySN+"' class='int lastDeployId'>"+res.lastDeployId+"</td><td deliverySN='"+deliverySN+"' class='left zhTwN lastDeployerName'>"+res.lastDeployerName+"</td><td deliverySN='"+deliverySN+"' class='left engN lastDeployDT'>"+res.lastDeployDT+"</td><td><ul class='file engN'></ul></td><td><ul class='zhTwN req'></ul></td><td><textarea class='zhTwN' readonly>"+res.deliveryComment+"</textarea></td></tr>";	
					}
					
					$("#tbodyFile").append(tmp);
					
					
					if( statusSN == "2" ) {	//完成寄發通知待提領
						//提領程式
						$("button[tarDeliverySN='"+res.deliveryTarSN+"']").button().bind("click",function(){ withdraw(this); });
					} else if( statusSN == "6" || statusSN == "8" ) {	//6 已提領待送審, 8 部署申請未通過
						if( isDepApplyNeed ==="true" ) {	//要部署要先申請
							//申請部署許可 
							$("button[tarDeliverySN='"+res.deliveryTarSN+"']").button().bind("click",function(){ apply4Deploy(this); });
						} else {				//不用申請即可部署
							//改變狀態的文字
							$("button[tarDeliverySN='"+res.deliveryTarSN+"']").button().parent("td").next().next().next().html("待部署");
							//改變綁定的函式
							$("button[tarDeliverySN='"+res.deliveryTarSN+"']").button().bind("click",function(){ validate(this); });
						}
					} else if( statusSN == "3" || statusSN == "9" || statusSN == "10" || statusSN == "12") {	//3 已提領待部署, 9 待部署, 10 部署失敗, 12 已確認成功
						//部署
						$("button[tarDeliverySN='"+res.deliveryTarSN+"']").button().bind("click",function(){ validate(this); });
					} else {
						//按鈕 disabled
						$("button[tarDeliverySN='"+res.deliveryTarSN+"']").button().attr("disabled",true);
					}
					
					$.each(res.files, function(j,file) {
						var fileVer = file.targetVer;
						if ( fileVer=="0" ) {
							fileVer = "&nbsp;";
						}
						tmp = "<li ver='"+file.targetVer+"' fn='"+file.fileName+"'>"+file.fileName+"&nbsp;"+fileVer+"("+file.localVer+")</li>";
						$("#tbodyFile ul.file:last").append(tmp);	
					});
				
					$.each(res.reqs, function(j,req) {
						tmp = "<li>"+req.reqSID+"&nbsp;-&nbsp;"+req.reqDesc+"</li>";
						$("#tbodyFile ul.req:last").append(tmp);	
					});
				});
				refreshUI(1,"tbodyFile",false);
				$("#tbodyFile tr:first td:first").attr("rowspan",$("#tbodyFile tr").size() );
			}
		},error : function(xhr, ajaxOptions, thrownError) { errorAjx(xhr); }
	});
	
	$("button").button();
	$("#radioUrgent").buttonset();
	$("#radioEnvSet").buttonset();
	windowUnfreeze();
});
</script>

</head>
<body>
	<div id="header"></div>
	
	<p>
	<img src="pic/wd.png" > 
	<p>
	<table id="tableFile">
		<thead class="tableFirst">
			<tr><td>&nbsp;</td><td class="left" colspan="9"></td></tr>
			<tr><td class="left zhTwN"><div id="radioUrgent">是否為緊急上線：<input type="radio" id="yesUrgent" name="emer" value='t'><label for="yesUrgent">是</label><input type="radio" id="noUrgent" name="emer" value='f'><label for="noUrgent">否</label></div></td><td class="left" colspan="9"><div id="radioEnvSet">部署環境：</div></td></tr>
			<tr><th>執行動態</th><th>&nbsp;</th><th>#</th><th>交付<br>代號</th><th>狀態</th><th>交付時間</th><th>最後<br>上線序號</th><th>最後<br>部署人員</th><th>最後<br>部署時間</th><th>部署檔案</th><th>相關需求</th><th>註解</th></tr>
			<tr><td colspan="11">&nbsp;</td></tr>
		</thead>
		
		<tbody id="tbodyFile"></tbody>
	</table>
</body>

<div class="dialog" id="dialogPerformDeployment">
	<table id="tablePerformDeployment">
		<thead id="theadPerformDeployment">
			<tr><th>已完成</th><th>待部署</th></tr>
		</thead>
		<tbody id="tbodyPerformDeployment">
			<tr>
				<td><select id="selectPerformed" size="5" multiple></select></td>
				<td><select id="selectNotPerformed" size="5" multiple></select></td>
			</tr>
		</tbody>
	</table>
</div>

</html>